<?php
/**
 * Created by PhpStorm.
 * User: renshan
 * Date: 16-6-18
 * Time: 下午9:24
 */

namespace ApiBundle\EventListener;

use ApiBundle\Exception\AppTokenInvalidException;
use ApiBundle\Security\AppTokenInterface;
use UserBundle\Security\UserTokenInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use ApiBundle\Exception\UserTokenNotFoundException;

/**
 * Class ApiTokenListener
 * @package ApiBundle\EventListener
 * 监听每个需要验证api_token的请求,并验证请求中的api_token
 */
class AppTokenListener
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();

        if (!is_array($controller)) {
            return;
        }

        /**
         * 如果要请求的Controller实现了ApiTokenInterface
         * 则需要验证api_token并，找到用户。
         * 如果通过aoi_token找不到用户，则抛出一个ApiTokenNotFoundException
         */
        if ($controller[0] instanceof AppTokenInterface) {
            $app_token = $this->container->getParameter('app_token');
            $request_token  =   $event->getRequest()->get('app_token');
            if(!$app_token || $app_token !== $request_token) {
                throw new AppTokenInvalidException(403);
            }
        }
    }
}